<template>
  <Layout>
      <Form :label-width="120" ref="formInline" :model="formInline">
        <Row  class="query-form">
          <Col span="8">
                  <FormItem label="类型：" prop="bsaeQstInfo">
                      <Select v-model="formInline.questionType">
                          <Option v-for="item in typeList" :value="item.value" :key="item.value">{{ item.label }}</Option>
                      </Select>
                  </FormItem>
          </Col>
          <Col span="8">
                  <FormItem label="标题：" prop="questionInfo">
                      <Input v-model="formInline.questionInfo" />
                  </FormItem>
          </Col>
          <Col span="8">
              <Button @click="cancel" class="ivu-btn-reset">重置</Button>
              <Button class="ivu-btn-query" icon="md-search" @click="query">查询</Button>
          </Col>
        </Row>
      </Form>
      <Row type="flex" justify="start" v-show="this.$route.query.type">
        <Col span="24" class="query-form">
          <Button size="large" class="ivu-btn-add" icon="md-add" @click="addModel">新增</Button>
            <Button @click="goback" class="ivu-btn-add">返回</Button>
        </Col>
      </Row>
      <Table ref='table'  :loading="loading" border :columns="questionColumns"
             :data="questionData"  no-data-text="没有查询到相关数据!"  :height="tableHeight" highlight-row stripe size="small"></Table>
     <Row style="margin-right:10px;">
        <Col span="24">
            <Page :total="pagedata.total" :current="pagedata.currentPage" :page-size="pagedata.pageSize"
                  @on-page-size-change="pageSizeChange" @on-change="pageChange" :page-size-opts="pageSizeArray" show-total show-sizer show-elevator />
        </Col>
      </Row>
      <Modal v-model="modal1" title="试题配置" width="800" :mask-closable="false">
          <Form :label-width="100" ref="formCustom" :model="form1data" :rules="ruleCustom">
              <Row>
                  <i-col>
                      <FormItem label="试题标题：" prop="questionInfo">
                          <Input v-model="form1data.questionInfo" placeholder="请输入..."
                                 show-word-limit :maxlength="1000"
                                 type="textarea" :autosize="{minRows:1,maxRows:5}"/>
                      </FormItem>
                  </i-col>
              </Row>
              <Row>
                  <i-col>
                      <FormItem label="试题类型：" prop="questionType">
                          <Select v-model="form1data.questionType" @on-change="questionTypeChange">
                              <Option v-for="item in typeList" :value="item.value" :key="item.value">{{ item.label }}</Option>
                          </Select>
                      </FormItem>
                  </i-col>
              </Row>
              <Row v-if="form1data.questionType==='judge'">
                  <i-col>
                      <FormItem label="正确答案：">
                          <Input v-model="form1data.remark" placeholder="判断题会用到..."
                                 type="textarea" :autosize="{minRows:1,maxRows:5}"/>
                      </FormItem>
                  </i-col>
              </Row>
              <div>
                  <Row class="query-form" v-show="this.$route.query.type&&form1data.questionType!='judge'">
                      <i-col>
                          <Button type="dashed" class="ivu-btn-add"  icon="md-add"  @click="addRow">添加</Button>
                      </i-col>
                  </Row>
                  <Row>
                      <i-col>
                          <Table ref='table2' border style="margin-top: 10px" :columns="detailColumns"
                                 :data="detailData" width="100%" stripe size="small"></Table>
                      </i-col>
                  </Row>
              </div>

          </Form>
          <div slot="footer">
            <Button  class='ivu-btn-save' v-show="this.$route.query.type" :loading="buttonLoading" @click="saveInfo">确定
            </Button>
            <Button class='ivu-btn-cancel' @click="closeModal">取消</Button>
          </div>
      </Modal>
    </Layout>
</template>

<script>

    import {Api} from '@/api/index.js'
    import qs from "qs";
    import {sessionStorage, cookie} from '@/common/cacheUtils.js';

    export default {
        name: "questionList",
        data(){
            return{
                buttonLoading:false,
                isUpdate: false,
                loading: true,
                loading2: true,
                questionId: '',
                formInline:{
                    questionType: '',
                    questionInfo: ''
                },
                typeList:[
                    {
                        value: 'radio',
                        label: '单选题'
                    },
                    {
                        value: 'checkbox',
                        label: '多选题'
                    },
                    {
                        value: 'judge',
                        label: '判断题'
                    },
                ],
                tableHeight: '',
                pageSizeArray: [10, 20, 50],
                pagedata: {
                    total: 0,
                    pageSize: 10,
                    currentPage: 1
                },
                modal1: false,
                questionColumns:[
                    {
                        type: 'index',
                        title: '编号',
                        width: 80,
                        align: 'center',
                        fixed: 'left'
                    },
                    {
                        title: '类型',
                        align: 'center',
                        width: 120,
                        key: 'questionType',
                        render:(h,params)=>{
                            return h('div',[
                                h('span',params.row.questionType == 'radio'?'单选题':params.row.questionType == 'checkbox'?'多选题':params.row.questionType == 'judge'?'判断题':'--')
                            ]);
                        }
                    },
                    {
                        title: '标题',
                        align: 'left',
                        key: 'questionInfo'
                    },
                    {
                        title: '操作',
                        align: 'center',
                        key: 'view',
                        fixed: 'right',
                        width: 140,
                        render: (h, params) => {
                            return h('div', [
                                h('A', {
                                    props: {
                                        type: 'primary',
                                        size: 'small'
                                    },
                                    style: {
                                        fontSize: '14px',
                                        // color: this.$route.query.type? '':'#d0d0d0' ,
                                        // pointerEvents: this.$route.query.type ? '' : 'none'
                                    },
                                    on: {
                                        click: () => {
                                            this.form1data = {...params.row};
                                            this.isUpdate = true;
                                            this.modal1 = true;
                                            this.detailData = [...params.row.questionDetailList]
                                        }
                                    }
                                }, this.$route.query.type?'修改':'详情'),
                                h('Divider', {
                                    props: {
                                        type: 'vertical',
                                    }
                                }, ''),
                                h('A', {
                                    props: {
                                        type: 'error',
                                        size: 'small'
                                    },
                                    style: {
                                        fontSize: '14px',
                                        color: this.$route.query.type? 'red':'#d0d0d0' ,
                                        pointerEvents: this.$route.query.type ? '' : 'none'
                                    },
                                    on: {
                                        click: () => {
                                            if (params.row.type == '0') {
                                                this.deleteRow(params.row);
                                            }else {
                                                this.$Message.error('当前试题在试卷中已有人作答，不可删除！');
                                            }
                                        }
                                    }
                                }, '删除')
                            ]);
                        }
                    }
                ],
                questionData: [],
                form1data: {},
                ruleCustom:{
                    questionInfo: [{
                        required: true,
                        message: '  ',
                        trigger: 'blur'
                    }],
                    questionType: [{
                        required: true,
                        message: '  ',
                        trigger: 'blur'
                    }]
                },
                detailColumns: [
                    {
                        type: 'index',
                        title: '编号',
                        width: 80,
                        align: 'center',
                        fixed: 'left'
                    },
                    {
                        title: '选项名称',
                        align: 'center',
                        key: 'answerOption',
                        render: (h, params) => {
                            // if(!this.isUpdate){
                                return h('div', [
                                    h('Input', {
                                        props: {
                                            type: "text",
                                            value: params.row.answerOption,
                                            readonly:this.form1data.questionType=='judge'
                                        },
                                        on: {
                                            "on-blur": event => {
                                                this.detailData[params.index]['answerOption'] = event.target.value;
                                                params.row.answerOption = event.target.value;
                                                this.$set(params.row, '$isEdit', false);
                                            },
                                        }
                                    }, ''),
                                ]);
                            // }else{
                            //     if (params.row.$isEdit) {
                            //         return h('div', [
                            //             h('Input', {
                            //                 props: {
                            //                     type: "text",
                            //                     value: params.row.answerOption
                            //                 },
                            //                 on: {
                            //                     "on-blur": event => {
                            //                         params.row.answerOption = event.target.value;
                            //                         this.$set(params.row, '$isEdit', false);
                            //                     },
                            //                 }
                            //             }, ''),
                            //         ]);
                            //     }else{
                            //         return h('div',[
                            //             h('span',params.row.answerOption || ' ')
                            //         ]);
                            //     }
                            // }
                        }
                    },
                    {
                        title: '是否正确选项',
                        align: 'center',
                        key: 'correctOption',
                        width: 120,
                        render: (h, params) => {
                            let value = false;
                            if(params.row.correctOption == 1){
                                value = true;
                            }
                            return h('div', [
                                h('i-switch', {
                                    props: {
                                        type: 'primary',
                                        size: 'small',
                                        value: value,
                                        disabled:!this.$route.query.type
                                    },
                                    on: {
                                        'on-change': (value) => {
                                            if(value){
                                                this.detailData[params.index]['correctOption'] = 1;
                                            }else{
                                                this.detailData[params.index]['correctOption'] = 0;
                                            }
                                        }
                                    }
                                }, ''),
                            ]);
                        }
                    },
                    {
                        title: '操作',
                        align: 'center',
                        key: 'view',
                        fixed: 'right',
                        width: 80,
                        render: (h, params) => {
                            return h('div', [
                                // h('A', {
                                //     props: {
                                //         type: 'primary',
                                //         size: 'small'
                                //     },
                                //     style: {
                                //         fontSize: '14px',
                                //     },
                                //     on: {
                                //         click: () => {
                                //             this.$set(params.row, '$isEdit', true);
                                //         }
                                //     }
                                // }, '修改'),
                                // h('Divider', {
                                //     props: {
                                //         type: 'vertical',
                                //     }
                                // }, ''),
                                h('A', {
                                    props: {
                                        type: 'error',
                                        size: 'small'
                                    },
                                    style: {
                                        fontSize: '14px',
                                        color: this.$route.query.type&&this.form1data.questionType!='judge'? 'red':'#d0d0d0' ,
                                        pointerEvents: this.$route.query.type&&this.form1data.questionType!='judge' ? '' : 'none'
                                    },
                                    on: {
                                        click: () => {
                                            this.detailData.splice(params.index,1);
                                            // if(this.isUpdate){
                                            //     // this.queryDetail(params.row.questionId);
                                            //     this.detailData.splice(params.index,1);
                                            // }else{
                                            //     this.detailData.splice(params.index,1);
                                            // }
                                        }
                                    }
                                }, '删除')
                            ]);
                        }
                    }
                ],
                detailData: [

                ]
            }
        },
        mounted(){
            this.tableHeight = window.innerHeight*0.85 - this.$refs.table.$el.offsetTop-40;
            this.query();
        },
        watch: {
            "modal1": function (qw, er) {
                if (qw && this.modal1) {
                } else {
                    this.query()
                }
            },
        },
        methods:{
            query(){
                this.loading = true;
                let data = {
                    page: this.pagedata.currentPage,
                    rows: this.pagedata.pageSize,
                    bsaeQstId: this.$route.query.bsaeQstId,
                };
                data = Object.assign(data,JSON.parse(JSON.stringify(this.formInline)));
                this.$http.get(Api.question,{
                    params:data,
                    paramsSerializer: params => {
                        return qs.stringify(params, { indices: false })
                    }
                }).then((res) => {
                    this.questionData = res.data.data.data;
                    this.pagedata.total = res.data.data.totalSize;
                    this.loading = false;
                }).catch( e => {
                    this.$Message.error('请求失败');
                });
            },
            pageSizeChange(pageSize){
                this.pagedata.pageSize = pageSize;
                this.query();
            },
            pageChange(pageNum){
                this.pagedata.currentPage = pageNum;
                this.query();
            },
            cancel(){
                this.formInline = {};
                this.query();
            },
            goback(){
                this.$router.go(-1);
            },
            addModel(){
                this.form1data = {
                    questionId :''
                };
                this.detailData=[]
                this.modal1 = true;
                this.isUpdate=false
            },
            saveInfo(){
                this.$refs['formCustom'].validate((valid) => {
                    if(valid){
                        let count = 0;
                        for(let i=0; i<this.detailData.length; i++){
                            this.detailData[i].orderNum=i
                            if(this.detailData[i].correctOption == 1){
                                count ++;
                            }
                        }
                        if(this.form1data.questionType == 'checkbox'){
                            if(count == 0){
                                this.$Message.error({
                                    content: '请至少选择一条正确选项！',
                                    duration: 4
                                });
                                return;
                            }
                        }else{
                            if(count == 0){
                                this.$Message.error({
                                    content: '请至少选择一条正确选项！',
                                    duration: 4
                                });
                                return;
                            }else if(count>1){
                                this.$Message.error({
                                    content: '请只选择一条正确选项！',
                                    duration: 4
                                });
                                return;
                            }
                        }
                        this.form1data.questionDetailList = this.detailData;
                        this.buttonLoading = true;
                        this.form1data.bsaeQstId = this.$route.query.bsaeQstId;
                        this.$http.post(Api.question, this.form1data).then((res) => {
                            this.query();
                            this.$Message.success({
                                content: '成功',
                                duration: 4
                            });
                            this.modal1 = false;
                          this.buttonLoading = false;
                        }).catch( e => {
                            this.$Message.error({
                                content: '请求失败',
                                duration: 4
                            });
                          this.buttonLoading = false;
                        });
                    }else {
                        this.$Message.error('请填报完整!');
                    }
                })
            },
            deleteRow(row){
                this.$Modal.confirm({
                    title: '数据删除',
                    content: '<p>确定删除该试题</p>',
                    okText: '确认',
                    onOk: () => {
                        this.$http.delete(Api.question+'/'+row.questionId, {params:{
                                questionId: row.questionId
                            }}).then((res) => {
                            this.$Message.success({content:'确认成功',duration: 4});
                            this.modal1 = false;
                            this.query();
                        })
                    },
                    cancelText: '取消'
                });
            },
            closeModal(){
                this.form1data = {};
                this.modal1 = false;
            },
            questionTypeChange(value){
                if (value == 'judge') {
                    this.detailData=[
                        {"answerOption":"正确", "correctOption":"1", "questionId": this.form1data.questionId, "questionDetailId": this.uuid()},
                        {"answerOption":"错误", "correctOption":"0", "questionId": this.form1data.questionId, "questionDetailId": this.uuid()}
                    ]
                }
            },
            addRow(){
                this.detailData.push({"answerOption":"", "correctOption":"", "questionId": this.form1data.questionId, "questionDetailId": this.uuid()});
            },

            uuid() {
                let s = [];
                let hexDigits = "0123456789abcdef";
                for (let i = 0; i < 32; i++) {
                    s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
                }
                s[14] = "4";  // bits 12-15 of the time_hi_and_version field to 0010
                s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1);  // bits 6-7 of the clock_seq_hi_and_reserved to 01
                let uuid = s.join("");
                return uuid
            }
        }
    }
</script>


<style lang='css' scoped>
@import '../../../../index.css';
</style>
